import os, re, insert


filename = "students.txt"


def menu():
    print('''
    ╔———————————————学生信息管理系统———————————————╗
    │                                              │
    │   =============== 功能菜单 ===============   │
    │                                              │
    │   1 录入学生信息                             │
    │   2 查找学生信息                             │
    │   3 删除学生信息                             │
    │   4 修改学生信息                             │
    │   5 排序                                     │
    │   6 统计学生总人数                           │
    │   7 显示所有学生信息                         │
    │   0 退出系统                                 │
    │  ==========================================  │
    │  说明：通过数字或↑↓方向键选择菜单            │
    ╚——————————————————————————————————————————————╝
    ''')


# def save(student):
#     try:
#         students_txt = open(filename, "a")
#     except Exception as e:
#         students_txt = open(filename, "w")
#     for info in student:
#         students_txt.write(str(info) + '\n')
#     students_txt.close()


# def insert():
#     student_list = []
#     mark = True
#     while mark:
#         id = input("请输入ID(如：1001)：")
#         if not id:
#             break
#         name = input("请输入名字：")
#         if not name:
#             break
#         try:
#             english = int(input("请输入英语成绩"))
#             python = int(input("请输入python成绩："))
#             c = int(input("请输入C语言成绩："))
#         except:
#             print("输入无效，不是整数数值....重新录入信息")
#             continue
#         student = {"id": id, "name": name, "english": english, "python": python, "c": c}
#         student_list.append(student)
#         input_mark = input("是否继续添加?(y/n):")
#         if input_mark == "y":
#             mark = True
#         else:
#             mark = False
#         save(student_list)
#         print("学生信息录入完毕！！！")


def delete():
    mark = True
    while mark:
        student_id = input("请输入要删除的学生ID:")
        if student_id is not "":
            if os.path.exists(filename):
                with open(filename, 'r') as rfile:
                    student_old = rfile.readlines()
            else:
                student_old = []
            ifdel = False
            if student_old:
                with open(filename, 'w') as wfile:
                    d = {}
                    for list in student_old:
                        d = dict(eval(list))
                        if d['id'] != student_id:
                            wfile.write(str(d)+"\n")
                        else:
                            ifdel = True
                    if ifdel:
                        print("ID为%s 的学生信息已经被删除..." % student_id)
                    else:
                        print("没有找到ID为%s的学生信息..." % student_id)
            else:
                print("无学生信息...")
                break
            show()
            input_mark = input("是否继续删除？(y/n):")
            if input_mark == 'y':
                mark = True
            else:
                mark = False


def modify():
    show()
    if os.path.exists(filename):
        with open(filename, "r") as rfile:
            students_old = rfile.readlines()
    else:
        return
    student_id = input("请输入要修改的学生ID:")
    with open(filename,"w") as wfile:
        for student in students_old:
            d = dict(eval(student))
            if d["id"] == student_id:
                print("找到了这名学生，可以修改信息了！")
                while True:
                    try:
                        d["name"] = input("请输入姓名：")
                        d["english"] = input("请输入english语言成绩：")
                        d["python"] = input("请输入python成绩：")
                        d["c"] = input("请输入C语言成绩：")
                    except:
                        print("你输入的有误，请重新输入：")
                    else:
                        break
                student = str(d)
                wfile.write(student+"\n")
                print("修改成功！")
            else:
                wfile.write(student)
    mark = input("是否继续修改其他学生信息？(y/n):") 
    if mark == 'y':
        modify()
     
             
def search():
    mark = True
    student_query = []
    while mark:
        id = ""
        name = ""
        if os.path.exists(filename):
            mode = input("按ID查输入1;按姓名查输入2：")
            if mode == "1":
                id = input("请输入学生ID:")
            elif mode == "2":
                name = input("请输入学生姓名：")
            else:
                print("你的输入有误,请重新输入！")
                search()
            with open(filename, "r") as rfile:
                students = rfile.readlines()
                for list in students:
                    d = dict(eval(list))
                    if d['id'] is not "":
                        if d['id'] == id:
                            student_query.append(d)
                    elif d['name'] is not "":
                        if d['name'] == name:
                            student_query.append(d)
                show_student(student_query)
                student_query.clear()
                inputMark = input("是否继续查询？()y/n：")
                if inputMark == 'y':
                    mark = True
                else:
                    mark = False
        else:
            print('暂未保存数据信息...')
            return


def show_student(studentList):
    if not studentList:
        print("无数据信息\n")
        return
    format_title = "{:^6}{:^8}{:^8}\t{:^10}\t{:^10}\t{:^10}"
    print(format_title.format("id", "名字", "英语成绩", "python成绩", "C语言成绩", "总成绩"))
    format_data = "{:^6}{:^10}{:^12}\t{:^12}\t{:^12}\t{:^12}"
    for info in studentList:
        id = info.get("id")
        name = info.get("name")
        english = info.get("english")
        python = info.get("python")
        c = info.get("c")
        print(format_data.format(id, name, english, python, c, int(english) + int(python) + int(c)))


def total():
    if os.path.exists(filename):
        with open(filename,"r") as rfile:
            student_len = rfile.readlines()
            if student_len:
                print("一共有%d名学生！" % len(student_len))
            else:
                print("还没有录入学生信息！")
    else:
        print("还没有学生信息！")


def show():
    student_new = []
    if os.path.exists(filename):
        with open(filename, "r") as rfile:
            student_old = rfile.readlines()
        for list in student_old:
            student_new.append(eval(list))
        if student_new:
            show_student(student_new)
            print("显示完毕！按回车键回到主界面...")
    else:
        print("暂未保存数据信息...")
    a = input("")



def main():
    ctrl = True
    while ctrl:
        menu()
        option = input('请选择：')
        option_str = re.sub("\D", "", option)
        if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
            option_int = int(option_str)
            if option_int == 0:
                print('你已退出学生信息管理系统！')
                ctrl = False
            elif option_int == 1:
                insert.insert()
            elif option_int == 2:
                search()
            elif option_int == 3:
                delete()
            elif option_int == 4:
                modify()
            elif option_int == 5:
                sort()
            elif option_int == 6:
                total()
            elif option_int == 7:
                show()


if __name__ == "__main__":
    main()
